import Taro from "@tarojs/taro";
import { error } from "@/utils/alert";
import { AbstractButton, Icon, Layout, UserSubPageBase } from "@/components";
import { Button, Input, Label, Picker, View } from "@tarojs/components";
import { useUserInfo, setUserData } from "@/store/userDataContext";
import { useAuth } from "@/store/authContext";
import { useEffect, useState } from "react";
import { switchTab } from "@/utils/navigation";
import { DateShape } from "@/data/shared/timeTypes";
import { TITLES_SELECT } from "@/data/user/userData";
import style from "./index.module.scss";

export default function UserDetailsEdit() {
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { userData } = userInfoState;
  const { userInfo } = userData!;
  const { dispatchAuthAction } = useAuth();

  // TODO: depending on Luke check
  // const bindPhone = useAuth()?.handleBindPhone;

  // useEffect(() => {
  //   if (!userInfo) {
  //     getUserData(dispatchUserDataAction， );
  //   }
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, [dispatchUserDataAction]);

  useEffect(() => {
    setTitle(userInfo?.title);
    setName(userInfo?.nickName);
    setPhone(userInfo?.phoneNumber);
    setEmail(userInfo?.email);
    setRegion(userInfo?.residenceArea);
    setBirthday(userInfo?.birthDay);
  }, [userInfo]);

  const [title, setTitle] = useState(userInfo?.title);
  const [name, setName] = useState(userInfo?.nickName);
  const [phone, setPhone] = useState(userInfo?.phoneNumber);
  const [email, setEmail] = useState(userInfo?.email);
  const [region, setRegion] = useState(userInfo?.residenceArea);
  const [birthDay, setBirthday] = useState(userInfo?.birthDay);

  const handleChangeUserInfo = () => {
    if (!userData?.likedItems.length) {
      setUserData(dispatchUserDataAction, userData!, {
        method: "POST",
        query: {
          nickname: name,
          birthday: birthDay,
          sex: title === "先生" ? 1 : 2,
          email: email,
          phone: phone,
          address: region,
        },
        authDispatch: dispatchAuthAction,
      });
      switchTab("pages/user/index");
    }
  };

  const handleFetchMobileNumber = (e) => {
    Taro.showLoading();
    Taro.login({
      success(res: any) {
        if (res.code) {
          Taro.request({
            url: `${process.env.apiEndpoint}/wechat/phone/decryption`,
            method: "POST",
            data: {
              code: res.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
            },
            success: function (f: any) {
              if (f.data.code !== 200) {
                error("获取失败，请重试");
              } else {
                Taro.hideLoading();
                setPhone(f.data.message);
              }
            },
            fail: function (f) {
              error(f.errMsg);
            },
          });
        }
      },
    });
  };

  useEffect(() => {}, [region]);

  return (
    <Layout>
      <UserSubPageBase title="个人信息" subTitleDark="请填写个人信息">
        <View className={style.form}>
          <View className={style["input-section"]}>
            <Label>称谓</Label>
            <Picker
              className={style.input}
              range={TITLES_SELECT}
              onChange={(e) => {
                setTitle(TITLES_SELECT[e.detail.value]);
              }}
            >
              <View className={style.flex}>
                <View>{title ? title : "请选择称谓"}</View>
                <Icon className={style.down} type="DownChevron" />
              </View>
            </Picker>
          </View>
          {/* Name */}
          <View className={style["input-section"]}>
            <Label>姓名</Label>
            <Input
              className={style.input}
              type="text"
              onInput={(e) => {
                setName(e.detail.value);
              }}
              value={name}
            />
          </View>
          {/* Phone */}
          <View className={style["input-section"]}>
            <Label>电话</Label>
            <View className={style.input}>{phone}</View>
            <Button
              plain
              className={style["wechat-phone-button"]}
              openType="getPhoneNumber"
              onGetPhoneNumber={handleFetchMobileNumber}
            >
              <View>授权使用手机号</View>
            </Button>
          </View>
          {/* Email */}
          <View className={style["input-section"]}>
            <Label>邮箱</Label>
            <Input
              className={style.input}
              type="text"
              onInput={(e) => {
                console.warn("currently no email-input validation");
                setEmail(e.detail.value);
              }}
              value={email}
            />
          </View>
          {/* Region */}
          <View className={style["input-section"]}>
            <Label>省-市-区</Label>
            <Picker
              className={style.input}
              mode="region"
              onChange={(e) => {
                setRegion(e.detail.value);
              }}
              value={region ? region : []}
            >
              <View className={style.flex}>
                <View>{region ? region.join("-") : ""}</View>
                <Icon className={style.down} type="DownChevron" />
              </View>
            </Picker>
          </View>
          {/* Birth Date */}
          <View className={style["input-section"]}>
            <Label>生日</Label>
            <Picker
              className={style.input}
              mode="date"
              onChange={(e) => {
                setBirthday(e.detail.value as DateShape);
              }}
              value={birthDay ? birthDay : ""}
            >
              <View className={style.flex}>
                <View>{birthDay}</View>
                <Icon className={style.down} type="DownChevron" />
              </View>
            </Picker>
          </View>
        </View>
        {/* Submit button */}
        <AbstractButton
          className={style["submit-button"]}
          color="dark"
          onClick={handleChangeUserInfo}
        >
          完成
        </AbstractButton>
      </UserSubPageBase>
    </Layout>
  );
}
